package org.example.juc.lock.demo;

import java.util.concurrent.Semaphore;

/**
 * @author songyafei
 */
public class SemaPhoreTest {
    static Semaphore semaphore = new Semaphore(5);
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            new Thread(new Car(i,semaphore)).start();
        }
    }


    static class  Car implements  Runnable{
        int i=0;
        Semaphore semaphore;

        public Car(int i, Semaphore semaphore) {
            this.i = i;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {

            try {
                Thread.sleep(3000);
                semaphore.acquire();
                System.out.println("当前线程："+Thread.currentThread().getName()+"获取到令牌"+i);
                Thread.sleep(5000);
                System.out.println("当前线程："+Thread.currentThread().getName()+"释放令牌"+i);

                semaphore.release();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
